from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from .serializers import UserRegisterSerializer, UserSerializer
from .models import User
import jwt
from django.conf import settings

class RegisterView(APIView):
    """用户注册视图"""
    permission_classes = []


    def post(self, request):
        # 使用专门处理注册的序列化器
        serializer = UserRegisterSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            return Response({
                'message': '注册成功（明文密码）',
                'user_id': user.id
            }, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=400)

class LoginView(APIView):
    """用户登录视图"""
    permission_classes = []
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')

        try:
            user = User.objects.get(username=username)
            if user.password == password:  # 直接明文比较
                return Response({
                    'status': '登录成功',
                    'user_id': user.id,
                    'username': user.username
                })
            return Response({'error': '密码错误'}, status=400)
        except User.DoesNotExist:
            return Response({'error': '用户不存在'}, status=404)

class LogoutView(APIView):
    """用户登出视图"""
    permission_classes = []

    def post(self, request):
        # 前端需要清除本地存储的token
        return Response({
            'message': '登出成功'
        })

class UserProfileView(APIView):
    """用户信息视图"""
    permission_classes = []

    def get(self, request):
        """获取用户信息"""
        try:
            user = User.objects.get(id=request.GET.get('user_id'))
            return Response({
                'username': user.username,
                'join_date': user.date_joined.strftime('%Y-%m-%d')
            })
        except User.DoesNotExist:
            return Response({'error': '用户不存在'}, status=404)

    def put(self, request):
        """更新用户信息"""
        try:
            user = User.objects.get(id=request.data.get('user_id'))
            
            # 验证原密码
            if not user.check_password(request.data.get('old_password')):
                return Response({'error': '原密码错误'}, status=400)
            
            # 更新用户名
            if 'username' in request.data:
                user.username = request.data['username']
            
            # 更新密码
            if 'new_password' in request.data:
                user.set_password(request.data['new_password'])
            
            user.save()
            return Response({'message': '更新成功'})
        except User.DoesNotExist:
            return Response({'error': '用户不存在'}, status=404)


class UserView(APIView):
    permission_classes = []

    def get(self, request, user_id=None):
        # 如果提供了 user_id，查询特定用户
        if user_id:
            try:
                user = User.objects.get(id=user_id)
                serializer = UserSerializer(user)
                return Response(serializer.data)
            except User.DoesNotExist:
                return Response({
                    'status': 'error',
                    'message': '用户不存在'
                }, status=status.HTTP_404_NOT_FOUND)

        # 如果没有提供 user_id，查询所有用户
        users = User.objects.all()
        serializer = UserSerializer(users, many=True)
        return Response(serializer.data)